package com.wardrobe.soa.common;

import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * Created by m1304 on 2018/8/2.
 */
@Controller
@RequestMapping("/api/tools")
public class ToolsController {

    @Resource
    private QiniuFileUploadClient qiniuFileUploadClient;
    @Value("${static_resource.domain}")
    private String domain;
    @Value("${static_resource.businessType}")
    private String businessType;

    private String zip = "zip";
    private Set<String> audios = Sets.newHashSet("mp3", "flac", "ape", "wav", "aac", "ogg", "wma");
    private Set<String> imgs = Sets.newHashSet("jpg", "png", "gif", "jpeg");
    private Set<String> videos = Sets.newHashSet("mp4");
    private String js = "js";
    private String css = "css";
    private String asp = "asp";

    private Logger logger = LoggerFactory.getLogger(ToolsController.class);

    private String uploadToQiniu(byte[] dataArr, String business, String fileType, String extName) throws Exception {
        String fullPicUrl = "";
        try {
            fullPicUrl = qiniuFileUploadClient.fileUpload(dataArr, business, fileType, extName);
        } catch (Exception e) {
            logger.error("QiniuFileUploadClient upload exception:", e);
            fullPicUrl = qiniuFileUploadClient.fileUpload(dataArr, business, fileType, extName);
        }
        return String.format(domain, (new Random()).nextInt(4) + 1) + fullPicUrl;
    }

    private String uploadToQiniu(String name, byte[] dataArr, String business, String fileType, String extName) throws Exception {
        String fullPicUrl = "";
        try {
            fullPicUrl = qiniuFileUploadClient.fileUpload(name, dataArr, business, fileType, extName);
        } catch (Exception e) {
            logger.error("QiniuFileUploadClient upload exception:", e);
            fullPicUrl = qiniuFileUploadClient.fileUpload(dataArr, business, fileType, extName);
        }
        return String.format(domain, (new Random()).nextInt(4) + 1) + fullPicUrl;
    }

    private String uploadToQiniuById(byte[] dataArr, String business, String fileType, String extName, String id) throws Exception {
        String fullPicUrl = "";
        try {
            fullPicUrl = qiniuFileUploadClient.uploadById(dataArr, business, fileType, extName, id);
        } catch (Exception e) {
            logger.error("QiniuFileUploadClient upload exception:", e);
            fullPicUrl = qiniuFileUploadClient.uploadById(dataArr, business, fileType, extName, id);
        }
        return String.format(domain, (new Random()).nextInt(4) + 1) + fullPicUrl;
    }

    @RequestMapping(value = "/upload_file", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upload_file(@RequestParam("Filedata") MultipartFile multipartFile) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            if (StringUtils.isNotBlank(multipartFile.getOriginalFilename())) {
                byte[] dataArr = multipartFile.getBytes();
                String file_ext_name = getExtFileName(multipartFile.getOriginalFilename());
                String fileName = getFileName(multipartFile.getOriginalFilename());
                String fileUrl = "";
                if (imgs.contains(file_ext_name)) {//图片返回宽高
                    fileUrl = uploadToQiniu(fileName, dataArr, businessType, "img", file_ext_name);
                    BufferedImage tmpImage = ImageIO.read(multipartFile.getInputStream());
                    retMap.put("width", tmpImage.getWidth());
                    retMap.put("height", tmpImage.getHeight());
                } else if (audios.contains(file_ext_name)) {
                    fileUrl = uploadToQiniu(dataArr, businessType, "audio", file_ext_name);
                } else if (videos.contains(file_ext_name)) {
                    fileUrl = uploadToQiniu(dataArr, businessType, "video", file_ext_name);
                } else if (zip.equals(file_ext_name)) {
                    fileUrl = uploadToQiniu(dataArr, businessType, "zip", file_ext_name);
                } else if (js.equals(file_ext_name)) {
                    fileUrl = uploadToQiniu(fileName, dataArr, businessType, "js", file_ext_name);
                } else if (css.equals(file_ext_name)) {
                    fileUrl = uploadToQiniu(fileName, dataArr, businessType, "css", file_ext_name);
                } else if (asp.equals(file_ext_name)) {
                    fileUrl = uploadToQiniu(fileName, dataArr, businessType, "css", file_ext_name);
                } else {
                    retMap.put("status", 0);
                    retMap.put("error", "上传文件类型不支持!");
                    return retMap;
                }
                retMap.put("status", 1);
                retMap.put("fileUrl", fileUrl);
            } else {
                retMap.put("status", 0);
                retMap.put("error", "上传文件不能为空!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            retMap.put("status", 0);
            retMap.put("error", "上传文件出错!");
        }
        return retMap;
    }

    @RequestMapping(value = "/upload_file_for_id", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFileForId(@RequestParam("file") MultipartFile multipartFile, String code, String key) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            if (StringUtils.isNotBlank(multipartFile.getOriginalFilename())) {
                byte[] dataArr = multipartFile.getBytes();
                String file_ext_name = getExtFileName(multipartFile.getOriginalFilename());
                String fileUrl = "";
                String fileName = "";
                if (StringUtils.isNotBlank(code)) {
                    fileName += key + "_" + code + "_" + System.currentTimeMillis();
                } else {
                    fileName += System.currentTimeMillis();
                }
                if (imgs.contains(file_ext_name)) {//图片返回宽高
                    fileUrl = uploadToQiniuById(dataArr, businessType, "img", file_ext_name, fileName);
                    BufferedImage tmpImage = ImageIO.read(multipartFile.getInputStream());
                    retMap.put("width", tmpImage.getWidth());
                    retMap.put("height", tmpImage.getHeight());
                } else if (audios.contains(file_ext_name)) {
                    fileUrl = uploadToQiniuById(dataArr, businessType, "audio", file_ext_name, fileName);
                } else if (videos.contains(file_ext_name)) {
                    fileUrl = uploadToQiniuById(dataArr, businessType, "video", file_ext_name, fileName);
                } else if (zip.equals(file_ext_name)) {
                    fileUrl = uploadToQiniuById(dataArr, businessType, "zip", file_ext_name, fileName);
                } else if (js.equals(file_ext_name)) {
                    fileUrl = uploadToQiniuById(dataArr, businessType, "js", file_ext_name, fileName);
                } else if (css.equals(file_ext_name)) {
                    fileUrl = uploadToQiniuById(dataArr, businessType, "css", file_ext_name, fileName);
                } else if (asp.equals(file_ext_name)) {
                    fileUrl = uploadToQiniuById(dataArr, businessType, "css", file_ext_name, fileName);
                } else {
                    retMap.put("status", 0);
                    retMap.put("error", "上传文件类型不支持!");
                    return retMap;
                }
                retMap.put("status", 1);
                retMap.put("fileUrl", fileUrl);
            } else {
                retMap.put("status", 0);
                retMap.put("errror", "上传文件不能为空!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            retMap.put("status", 0);
            retMap.put("error", "上传文件出错!");
        }
        return retMap;
    }

    /**
     * 多文件上传
     * @param request
     * @param writer
     * @throws Exception
     */
    @RequestMapping(value = "/processUpload", method = RequestMethod.POST)
    public void processUpload(MultipartHttpServletRequest request, PrintWriter writer) throws Exception {
        StringBuilder result = new StringBuilder();
        Map<String, Object> retMap = new HashMap<String, Object>();
        Map<String, MultipartFile> fileMap = request.getFileMap();
        for (Map.Entry<String, MultipartFile> f : fileMap.entrySet()) {
            MultipartFile multipartFile = f.getValue();
            try {
                if (StringUtils.isNotBlank(multipartFile.getOriginalFilename())) {
                    byte[] dataArr = multipartFile.getBytes();
                    String file_ext_name = getExtFileName(multipartFile.getOriginalFilename());
                    String fileName = getFileName(multipartFile.getOriginalFilename());
                    String fileUrl = "";
                    if (imgs.contains(file_ext_name)) {//图片返回宽高
                        fileUrl = uploadToQiniu(fileName, dataArr, businessType, "img", file_ext_name);
                        BufferedImage tmpImage = ImageIO.read(multipartFile.getInputStream());
                        retMap.put("width", tmpImage.getWidth());
                        retMap.put("height", tmpImage.getHeight());
                        result.append("{").append('"').append("width").append('"').append(":").append(tmpImage.getWidth()).append(",").append('"').append("height").append('"').append(":").append(tmpImage.getHeight()).append(",");

                    } else if (audios.contains(file_ext_name)) {
                        fileUrl = uploadToQiniu(dataArr, businessType, "audio", file_ext_name);
                    } else if (videos.contains(file_ext_name)) {
                        fileUrl = uploadToQiniu(dataArr, businessType, "video", file_ext_name);
                    } else if (zip.equals(file_ext_name)) {
                        fileUrl = uploadToQiniu(dataArr, businessType, "zip", file_ext_name);
                    } else if (js.equals(file_ext_name)) {
                        fileUrl = uploadToQiniu(fileName, dataArr, businessType, "js", file_ext_name);
                    } else if (css.equals(file_ext_name)) {
                        fileUrl = uploadToQiniu(fileName, dataArr, businessType, "css", file_ext_name);
                    } else if (asp.equals(file_ext_name)) {
                        fileUrl = uploadToQiniu(fileName, dataArr, businessType, "css", file_ext_name);
                    } else {
                        retMap.put("status", 0);
                        retMap.put("error", "上传文件类型不支持!");
                        result.append('"').append("status").append('"').append(":").append(0).append(",").append('"').append("error").append('"').append(":").append("上传文件类型不支持!").append("}");
                        writer.write(retMap.toString());
                    }
                    retMap.put("status", 1);
                    retMap.put("fileUrl", fileUrl);
                    result.append('"').append("status").append('"').append(":").append(1).append(",").append('"').append("fileUrl").append('"').append(":").append('"').append(fileUrl).append('"').append("}");
                } else {
                    retMap.put("status", 0);
                    retMap.put("error", "上传文件不能为空!");
                    result.append('"').append("status").append('"').append(":").append(0).append(",").append('"').append("error").append('"').append(":").append("上传文件不能为空!").append("}");
                }
            } catch (Exception e) {
                e.printStackTrace();
                retMap.put("status", 0);
                retMap.put("error", "上传文件出错!");
                result.append('"').append("status").append('"').append(":").append(0).append(",").append('"').append("error").append('"').append(":").append("上传文件出错!").append("}");
            }
        }

        writer.write(result.toString());
    }

    private String getExtFileName(String base64FileName) {
        int idx = base64FileName.lastIndexOf(".");
        String file_ext_name = null;
        if (idx != -1) {
            file_ext_name = base64FileName.substring(idx + 1);
        }
        if (StringUtils.isBlank(file_ext_name) || "null".equalsIgnoreCase(file_ext_name)) {
            file_ext_name = "jpeg";
        }
        return file_ext_name;
    }

    private String getFileName(String base64FileName) {
        int idx = base64FileName.lastIndexOf(".");
        String fileName = null;
        if (idx != -1) {
            fileName = base64FileName.substring(0, idx);
        }
        return fileName;
    }

}
